// import useCode from '@renderer/hooks/useCode'
import { useStore } from '@renderer/store/useStore'
import { useCallback, useEffect } from 'react'

export default () => {
  // const { data, setData } = useCode()
  const data = useStore((state) => state.data)
  const setData = useStore((state) => state.setData)
  const setId = useStore((state) => state.setId)
  const id = useStore((state) => state.id)
  const setSearch = useStore((state) => state.setSearch)
  // const [currentIndex, setCurrentIndex] = useState(0)

  const handleKeyEvent = useCallback(
    (e: KeyboardEvent) => {
      switch (e.code) {
        case 'ArrowUp':
          {
            const index = data.findIndex((item) => item.id === id)
            setId(data[index - 1]?.id || data[data.length - 1].id)
          }
          // setCurrentIndex((currentIndex) => (currentIndex > 0 ? currentIndex - 1 : data.length - 1))
          break
        case 'ArrowDown':
          {
            const index = data.findIndex((item) => item.id === id)
            setId(data[index + 1]?.id || data[0].id)
          }
          // setCurrentIndex((currentIndex) => (currentIndex < data.length - 1 ? currentIndex + 1 : 0))
          break
        case 'Enter': {
          selectItemm(id)
          break
        }
        case 'Escape': {
          window.api.closeWindow('search')
        }
      }
    },
    [data, id],
  )
  async function selectItemm(id: number) {
    const content = data.find((item) => item.id === id)?.content
    content && (await navigator.clipboard.writeText(content))
    window.api.closeWindow('search')
    setData([])
    setSearch('')
  }
  useEffect(() => {
    document.addEventListener('keydown', handleKeyEvent)
    return () => {
      document.removeEventListener('keydown', handleKeyEvent)
    }
  }, [handleKeyEvent])
  useEffect(() => {
    setId(data[0]?.id || 0)
  }, [data])
  return {
    id,
    data,
    selectItemm,
  }
}
